package com.taotao.openapi2.controller;

import com.taotao.openapi2.common.RespData;
import com.taotao.openapi2.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Body;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Param;
import org.noear.solon.annotation.Post;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.core.handle.ModelAndView;
import org.noear.solon.core.handle.UploadedFile;
import org.noear.solon.validation.annotation.Valid;
import org.noear.solon.validation.annotation.Validated;

import java.io.File;
import java.io.IOException;


@Valid
@Slf4j
@Api(tags = "demo演示")
@Controller
@Mapping("/demo")
public class DemoController {

    @ApiOperation(value = "get演示1", notes = "")
    @Mapping(value = "/hello", method = MethodType.GET)
    public String hello(@ApiParam("名字") @Param(value = "name", defaultValue = "world") String name) {
        return String.format("Hello %s!", name);
    }


    @ApiOperation(value = "get演示2", notes = "")
    @Get
    @Mapping("/hello2")
    public RespData hello2(@ApiParam("名字") @Param(defaultValue = "world") String name) {
        return RespData.successResp();
    }


    @ApiOperation(value = "body的json参数", notes = "")
    @Post
    @Mapping("/addUser")
    public RespData<User> addUser(@Validated @Body User u) {

        log.info("-------------" + u);
        return RespData.successResp(u);
    }


    @ApiOperation(value = "上传文件", notes = "")
    @Post
    @Mapping("/upload")
    public String upload(@ApiParam("合同文件")UploadedFile file) {
        return file.getName();
    }

    @Post
    @Mapping("/upload2")
    public void upload2(@ApiParam("jpg文件")UploadedFile file) throws IOException {
        try{
            //可以同步处理，也可以异步
            file.transferTo(new File("/demo/user/logo.jpg"));
        } finally {
            //用完之后，删除"可能的"临时文件 //v2.7.2 后支持
            file.delete();
        }
    }

}